package com.study.sbsummary.config.database;

import com.baomidou.mybatisplus.extension.spring.MybatisSqlSessionFactoryBean;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.jdbc.DataSourceBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;

import javax.sql.DataSource;

/**
 *
 */
//@Configuration
//@MapperScan(basePackages = "com.truely.plog.serving.mapper.truely", sqlSessionFactoryRef = "truelyServeSqlSessionFactory")
public class TruelyServeMysqlConfig {
	@Bean(name = "truelyServeDataSource")
	@ConfigurationProperties(prefix = "spring.datasource.mysql.truely-serving")
	public DataSource getDateSource() {
		return DataSourceBuilder.create().build();
	}

	@Autowired
	private InterceptorConfig interceptorConfig;

	@Bean(name = "truelyServeSqlSessionFactory")
	@Autowired
	public SqlSessionFactory truelyServeSqlSqlSessionFactory(@Qualifier("truelyServeDataSource") DataSource datasource)
			throws Exception {
		MybatisSqlSessionFactoryBean bean = new MybatisSqlSessionFactoryBean();
		if (interceptorConfig.getInterceptors() != null) {
			bean.setPlugins(interceptorConfig.getInterceptors());
		}
		bean.setDataSource(datasource);
		bean.setMapperLocations(
				new PathMatchingResourcePatternResolver().getResources("classpath*:mapper/truely/*.xml"));
		return bean.getObject();
	}

	@Bean(name = "truelyTx")
	public DataSourceTransactionManager transactionManager(@Qualifier("truelyServeDataSource") DataSource dataSource) {
		return new DataSourceTransactionManager(dataSource);
	}

	@Bean("truelyServeSqlSessionTemplate")
	public SqlSessionTemplate truelyServeSqlSessionTemplate(
			@Qualifier("truelyServeSqlSessionFactory") SqlSessionFactory sessionFactory) {
		return new SqlSessionTemplate(sessionFactory);
	}
}
